package com.zhugang.week13.sort;

/**
 * @program algorithms
 * @description: SelectionSort
 * @author: chanzhugang
 * @create: 2022/10/17 23:38
 */
public class SelectionSort {

    /**
     * 选择排序
     *
     * @param arr
     * @param n
     */
    public void selectSort(int[] arr, int n) {
        // 每次从未排序区间选择最小值 放在已排序区间末尾(交换)
        for (int i = 0; i < n - 1; i++) {
            int minPos = i;
            for (int j = i; j < n; j++) {
                // i - n 中选择最小值
                if (arr[j] < arr[minPos]) {
                    // 更新最小值下标
                    minPos = j;
                }
            }
            // swap
            swap(arr, i, minPos);
        }
    }

    private void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    public static void main(String[] args) {
        SelectionSort selectionSort = new SelectionSort();
        int[] arr = new int[]{5, 3, 1, 4, 2};
        selectionSort.selectSort(arr, arr.length);
        for (int i : arr) {
            System.out.println(i);
        }

    }
}